package org.visionlibrary.event.bus;

import java.util.ServiceLoader;

import org.visionlibrary.event.bus.exception.EventBusPublishException;

/**
 * An {@link EventBus} factory that will return a singleton implementation
 * loaded via the Java 6 {@link ServiceLoader}. By default, without changes to
 * the jar, a {@link BasicEventBus} implementation will be returned via the
 * factory methods.
 * <p>
 * This static factory also includes the same methods as EventBus which will
 * delegate to the ServiceLoader loaded instance. Thus, the class creates a
 * convenient single location for which client code can be hooked to the
 * configured EventBus.
 */
public final class EventBusService {
	private EventBusService() {
		super();
	}
	
	private static final EventBus EVENTBUS;
	static {
		final ServiceLoader<EventBus> ldr = ServiceLoader.load(EventBus.class);
		EVENTBUS = ldr.iterator().next();
	}

	public static EventBus getInstance() {
		return EVENTBUS;
	}

	public static void subscribe(final Object subscriber) {
		EVENTBUS.subscribe(subscriber);
	}

	public static void unsubscribe(final Object subscriber) {
		EVENTBUS.unsubscribe(subscriber);
	}

	public static void publish(final Object event) throws EventBusPublishException {
		EVENTBUS.publish(event);
	}

	public static boolean hasPendingEvents() {
		return EVENTBUS.hasPendingEvents();
	}
}
